/*
 * @Author: ZhaoDong
 * @Date: 2022-07-28 16:36:23
 * @LastEditors: ZhaoDong
 * @LastEditTime: 2022-07-28 16:45:26
 * @Description: 取消重复请求
 */
import axios, { AxiosRequestConfig } from 'axios';

let requestMap = new Map();

export const getKey = (config: AxiosRequestConfig): string => [config.url, config.method].join('&');

export const addRequest = (config: AxiosRequestConfig) => {
  const pendingKey = getKey(config);
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken(cancel => {
      if (!requestMap.has(pendingKey)) {
        requestMap.set(pendingKey, cancel);
      }
    });
};

export const removeRequest = (config: AxiosRequestConfig) => {
  const pendingKey = getKey(config);
  if (requestMap.has(pendingKey)) {
    const cancelToken = requestMap.get(pendingKey);
    cancelToken(pendingKey);
    requestMap.delete(pendingKey);
  }
};

export const removeAllRequest = () => {
  requestMap.forEach((value, key) => {
    const cancelToken = requestMap.get(key);
    cancelToken(key);
    requestMap.delete(key);
  });
};
